<script lang="ts" setup>
import type { DefApplicationModel } from '#/api';

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH } from '@vben/constants';
import { useTabs } from '@vben/hooks';
import { useAccessStore, useUserStore } from '@vben/stores';
import { isUrl } from '@vben/utils';

import { useLoading } from '@vben-core/shadcn-ui';

import {
  checkEmployeeHaveApplication,
  findMyApplication,
  findRecommendApplication,
} from '#/api';
import { useMessage } from '#/hooks/web/useMessage';
import { useAuthStore } from '#/store';
import ApplicationCard from '#/views/_core/home/modules/application-card.vue';

const accessStore = useAccessStore();
const userStore = useUserStore();
const authStore = useAuthStore();
const router = useRouter();
const { createMessage, createConfirm } = useMessage();

const myApplicationList = ref();
const recommendApplicationList = ref();
onMounted(async () => {
  myApplicationList.value = await findMyApplication({});
  recommendApplicationList.value = await findRecommendApplication({});
});

function handleClick() {
  createMessage.warning('快联系公司管理员开通我吧~');
}

const [openFullLoading, closeFullLoading] = useLoading({
  text: '加载中...',
});

async function navTo(item: DefApplicationModel.DefApplicationResultVO) {
  if (accessStore.applicationId === item?.id) {
    createMessage.warn(`您当前正处于[${item.name}]，无需切换`);
    return;
  }
  if (!item || !item.id) {
    createMessage.error('请选择正确的应用进行切换');
  }
  try {
    openFullLoading();
    const canJump = await checkEmployeeHaveApplication(item?.id || '');
    if (!canJump) {
      createMessage.warn(
        `对不起，您无该应用访问权限，请联系贵公司管理员开通权限`,
      );
      return '';
    }
    const isOpen = item.url && isUrl(item.url);
    createConfirm({
      iconType: 'warning',
      content: `确定要${isOpen ? '跳转' : '切换'}到应用：【${
        item.name
      }】， 并重新加载其资源吗？`,
      onOk: async () => {
        if (isOpen) {
          window.open(item.url);
        } else {
          const { closeAllTabs } = useTabs();
          closeAllTabs();

          const fetchUserInfoResult = await authStore.fetchUserInfo();

          userStore.setUserInfo(fetchUserInfoResult);

          accessStore.setIsAccessChecked(false);
          accessStore.setApplicationId(item.id as string);
          accessStore.setApplicationName(item.name as string);

          if (accessStore.loginExpired) {
            accessStore.setLoginExpired(false);
          } else {
            createMessage.success(`成功切换到应用：[${item.name}]`);

            setTimeout(async () => {
              await router.replace({ path: DEFAULT_HOME_PATH });
              location.reload();
            }, 200);
          }
        }
      },
    });
  } finally {
    closeFullLoading();
  }
}
</script>

<template>
  <div class="enter-y w-full">
    <ApplicationCard
      :current-application-id="accessStore.applicationId"
      :items="myApplicationList"
      title="我的应用"
      @click="navTo"
    />

    <ApplicationCard
      :items="recommendApplicationList"
      title="推荐应用"
      @click="handleClick"
      class="enter-y !my-4"
    />
  </div>
</template>
